package cn.com.hhrcw.personal.wxlogin.web;

import cn.com.hhrcw.entity.CmsContent;
import cn.com.hhrcw.entity.MemberThird;
import cn.com.hhrcw.personal.wxlogin.params.WxConfirmParams;
import cn.com.hhrcw.personal.wxlogin.util.WxLoginTokenUtil;
import cn.com.hhrcw.service.ICmsContentService;
import cn.com.hhrcw.service.IMemberThirdService;
import cn.com.hhrcw.thirdLogin.vo.ThridLoginVO;
import cn.com.hhrcw.utils.Constant;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * 微信登录-公众号h5
 * @author lixingxing
 */
@Slf4j
@RestController
@RequestMapping("/personal/wxLogin/h5")
@Validated
public class WxLoginH5Controller extends JeecgController<CmsContent, ICmsContentService> {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IMemberThirdService memberThirdService;

    @Value("${spring.profiles.active}")
    private String profiles;

    /**
     * 确认登录、拒绝登录
     *
     * @return
     */
    @PostMapping(value = "/confirm")
    public Result<?> confirm(@RequestBody @Valid WxConfirmParams params) {//
        String token = params.getToken();
        String loginState = (String) redisTemplate.opsForValue().get(token);
        log.info("loginState： {} ,nickname: {}", loginState, params.getNickname());
        final long time = StrUtil.equals(profiles, "dev") ? (cn.com.hhrcw.personal.wxlogin.util.Constant.TIME_MIN * 24) : cn.com.hhrcw.personal.wxlogin.util.Constant.TIME_MIN;
        boolean equalsIgnoreCase = "refuse".equalsIgnoreCase(params.getOperType());
        if (StringUtils.isBlank(loginState)) {
            return Result.error(602, "二维码已失效，请重新扫描");
        } else if (equalsIgnoreCase) {
            log.info("用户拒绝登录");

            redisTemplate.opsForValue().set(token, cn.com.hhrcw.personal.wxlogin.util.Constant.REFUSE, time, TimeUnit.MINUTES);
            return Result.error(603, "拒绝登录");
        } else {

            //存储微信对象未将来手机号+验证码+公众号+openid 做准备
            ThridLoginVO t = new ThridLoginVO();
            t.setThirdKey(params.getUnionid());
            t.setThirdType(params.getThirdType());
            //设置openid
            t.setThirdSecondKey(params.getOpenid());
            t.setThirdName(params.getNickname());

            LambdaUpdateWrapper<MemberThird> wrapper = Wrappers.lambdaUpdate();
            wrapper.eq(MemberThird::getThirdSecondKey, params.getOpenid()).eq(MemberThird::getThirdType, Constant.THIRD_TYPE_WX_OA);
            MemberThird memberThird = memberThirdService.getOne(wrapper);
            //未绑定用户
            if (null == memberThird) {
                log.info("未绑定/未注册用户{}", params.getOpenid());

                redisTemplate.opsForValue().set(token, cn.com.hhrcw.personal.wxlogin.util.Constant.UNBIND, time, TimeUnit.MINUTES);
                redisTemplate.opsForValue().set(WxLoginTokenUtil.getWxThirdObjToken(token), t, 3, TimeUnit.HOURS);

                return Result.error(604, "未绑定用户");
            }
            //成功的用户
            else {
                log.info("合法，可登录的用户");

                redisTemplate.opsForValue().set(token, cn.com.hhrcw.personal.wxlogin.util.Constant.OK, time, TimeUnit.MINUTES);

                t.setUserId(memberThird.getUserId());
                redisTemplate.opsForValue().set(WxLoginTokenUtil.getWxThirdObjToken(token), t, time, TimeUnit.MINUTES);
                return Result.ok("ok");
            }

        }

    }

}
